package danran.dbapi.controller;

import danran.dbapi.domain.Token;
import danran.dbapi.service.TokenService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.UUID;

/**
 * @Classname TokenController
 * @Description TODO
 * @Date 2022/1/17 15:41
 * @Created by RanCoder
 */
@RestController
@RequestMapping("/token")
public class TokenController {

    private static final Logger log = LoggerFactory.getLogger(TokenController.class);

    @Autowired
    TokenService tokenService;

    @RequestMapping("/add")
    public void addToken(Token token) {
        token.setCreateTime(System.currentTimeMillis());
        tokenService.insert(token);
    }

    @RequestMapping("/getAll")
    public List<Token> getAllTokens() {
        return tokenService.getAll();
    }

    @RequestMapping("/delete/{id}")
    public void deleteToken(@PathVariable("id") Integer id) {
        tokenService.deleteById(id);
    }

    /**
     * 生成API授权token
     */
    @RequestMapping("/generate")
    public String generateToken() {
        String token = DigestUtils.md5DigestAsHex(UUID.randomUUID().toString().getBytes());
        log.info("Generate api token : {}", token);
        return token;
    }

    /**
     * 将api token授权给给定的 group
     *
     * @param tokenId
     * @param groupIds
     */
    @RequestMapping("/auth")
    public void authenticate(Integer tokenId, String groupIds) {
        tokenService.auth(tokenId, groupIds);
    }

    @RequestMapping("/getAuthGroups/{tokenId}")
    public List<String> getAuthGroups(@PathVariable Integer tokenId) {
        return tokenService.getAuthGroups(tokenId);
    }
}
